package com.phkj.qdh.ui.fragment.usecar

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import com.google.gson.reflect.TypeToken
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.TimePickerPopup
import com.phkj.qdh.bean.ApprovalManBean
import com.phkj.qdh.bean.CarKeyBean
import com.phkj.qdh.databinding.FragmentUseCarSubmitBinding
import com.phkj.qdh.ui.dialog.MyTimeSelectDialog
import com.phkj.qdh.ui.dialog.CommonSelectDialog
import com.phkj.qdh.ui.dialog.SelectManDialog
import com.phkj.qdh.ui.dialog.SelectManListener
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import kotlinx.coroutines.flow.collectLatest
import rxhttp.wrapper.utils.GsonUtil
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
import java.util.HashMap

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 提交用车申请
 */
class UseCarSubmitFragment : Fragment() {
    private var param1: String? = null
    private var param2: String? = null
    private var _binding: FragmentUseCarSubmitBinding? = null
    private val binding get() = _binding!!
    private val ysIdList = ArrayList<String>()
    private val ysNameList = ArrayList<String>()
    private val approverIdList = ArrayList<Int>()
    private val approverNameList = ArrayList<String>()
   private val format = SimpleDateFormat("yyyy-MM-dd HH:mm:00")
    private lateinit var vm: CarVM
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
        parentFragmentManager.setFragmentResultListener("car_select",this){requestKey, bundle ->
            if (requestKey == "car_select"){
                val carKeyList =  GsonUtil.fromJson<List<CarKeyBean>>(bundle.getString("list"),object :TypeToken<List<CarKeyBean>>(){}.type)
                val sb = StringBuilder()
                ysIdList.clear()
                ysNameList.clear()
                carKeyList.forEach {
                    sb.append(it.ysName)
                    sb.append("、")
                    ysIdList.add(it.ysId)
                    ysNameList.add(it.ysName)
                }
                binding.tvCar.text = if (sb.isNotEmpty()) sb.deleteCharAt(sb.length-1).toString() else ""
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentUseCarSubmitBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getCarVMProvider())[CarVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            llSelectCar.setOnClickListener {
                parentFragmentManager.commit {
                    addToBackStack("car_select")
                    replace(id, UseCarSubmitSelectCarFragment.newInstance("", ""))
                    setReorderingAllowed(true)
                }
            }
            llSelectStarDate.setOnClickListener {
//                setTime(tvStartDate)

                val dialog = MyTimeSelectDialog.newInstance(context = requireContext())
                dialog.setMode(TimePickerPopup.Mode.YMDHM)
//                format.parse(binding.tvStartDate.text.toString())?.let {
//                    val calender = Calendar.getInstance()
//                    calender.time = it
//                    dialog.setDefaultDate(calender)
//                }

                dialog.setTitle("请选择开始时间")
                dialog.setTimePickerListener(object : TimePickerListener {
                    override fun onTimeChanged(date: Date) {
                    }

                    override fun onTimeConfirm(date: Date, view: View) {

                        if (System.currentTimeMillis() >= date.time) {
                            ToastUtils.show("使用时间必须大于当前时间")
                            return
                        }
                        tvStartDate.text = format.format(date.time)
                    }

                    override fun onCancel() {
                    }
                })
                XPopup.Builder(requireContext()).enableDrag(false).asCustom(dialog).show()

            }
            llSelectEndDate.setOnClickListener {
                if (tvStartDate.text.toString().isBlank()){
                    ToastUtils.show("请先选择开始时间")
                    return@setOnClickListener
                }
                val dialog = MyTimeSelectDialog.newInstance(context = requireContext())
                dialog.setMode(TimePickerPopup.Mode.YMDHM)
//                format.parse(binding.tvStartDate.text.toString())?.let {
//                    val calender = Calendar.getInstance()
//                    calender.time = it
//                    dialog.setDefaultDate(calender)
//                }

                dialog.setTitle("请选择结束时间")
                dialog.setTimePickerListener(object : TimePickerListener {
                    override fun onTimeChanged(date: Date) {
                    }

                    override fun onTimeConfirm(date: Date, view: View) {

                        if (System.currentTimeMillis() >= date.time) {
                            ToastUtils.show("使用时间必须大于当前时间")
                            return
                        }

                        if (format.parse(binding.tvStartDate.text.toString()).time>=date.time){
                            ToastUtils.show("开始使用时间必须大于结束时间")
                            return
                        }
                        tvEndDate.text = format.format(date.time)
                    }

                    override fun onCancel() {
                    }
                })
                XPopup.Builder(requireContext()).enableDrag(false).asCustom(dialog).show()
//                setTime(tvEndDate)
            }
            llSelectMan.setOnClickListener { //选择审批人
                vm.getApprovalManList()
            }
            btnSubmit.setOnClickListener {
                submit()
            }
        }
        launchAndRepeatWithViewLifecycle {
            vm.carUseSubmit.collectLatest {
                if (it==0){
                    parentFragmentManager.commit {
                        addToBackStack("car_submit")
                        replace(id, UseCarSubmitFinishFragment.newInstance("", ""))
                        setReorderingAllowed(true)
                    }
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.approvalManBean.collectLatest {
                val dialog = SelectManDialog(requireContext(),it)
                dialog.setSelectManListener(object :SelectManListener{
                    override fun ok(list: List<ApprovalManBean>) {
                        val sb = StringBuilder()
                        approverIdList.clear()
                        list.forEach{bean->
                            sb.append(bean.name)
                            approverIdList.add(bean.userId)
                            approverNameList.add(bean.name)
                            sb.append("、")
                        }
                        binding.tvName.text = if (sb.length>1) sb.deleteCharAt(sb.length-1).toString() else ""
                    }
                })
                XPopup.Builder(requireContext()).dismissOnTouchOutside(true).asCustom(dialog)
                    .show()
            }
        }
    }

    private fun submit(){
        if (ysNameList.isEmpty()){
            ToastUtils.show("请选择车辆")
            return
        }
        if (binding.tvStartDate.text.toString().isBlank()){
            ToastUtils.show("请选择开始时间")
            return
        }
        if (binding.tvEndDate.text.toString().isBlank()){
            ToastUtils.show("请选择开始时间")
            return
        }

        if (System.currentTimeMillis()>=format.parse(binding.tvStartDate.text.toString()).time){
            ToastUtils.show("开始使用时间大于当前时间")
            return
        }

        if (format.parse(binding.tvStartDate.text.toString()).time>=format.parse(binding.tvEndDate.text.toString()).time){
            ToastUtils.show("开始使用时间必须小于结束时间")
            return
        }

        if (approverNameList.isEmpty()){
            ToastUtils.show("请选择审批人")
            return
        }
        val map = HashMap<String,Any?>()
        map["ysIdList"] = ysIdList
        map["ysNameList"] =ysNameList
        map["startTimeStr"] = binding.tvStartDate.text.toString()
        map["endTimeStr"] =  binding.tvEndDate.text.toString()
        map["applyRemark"] =  binding.edtReson.text.toString()
        map["approverIdList"] = approverIdList
        map["approverNameList"] = approverNameList
        vm.carUseSubmit(map)
    }

    private fun setTime(tv: TextView) {
        val format = SimpleDateFormat("yyyy-MM-dd HH:mm:00")
        val dialog = MyTimeSelectDialog.newInstance(context = requireContext())
        dialog.setMode(TimePickerPopup.Mode.YMDHM)
//                format.parse(binding.tvStartDate.text.toString())?.let {
//                    val calender = Calendar.getInstance()
//                    calender.time = it
//                    dialog.setDefaultDate(calender)
//                }

        dialog.setTitle("请选择开始时间")
        dialog.setTimePickerListener(object : TimePickerListener {
            override fun onTimeChanged(date: Date) {
            }

            override fun onTimeConfirm(date: Date, view: View) {

                if (System.currentTimeMillis() >= date.time) {
                    ToastUtils.show("使用时间必须大于当前时间")
                    return
                }
                tv.text = format.format(date.time)
            }

            override fun onCancel() {
            }
        })
        XPopup.Builder(requireContext()).enableDrag(false).asCustom(dialog).show()
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment UseCarSubmitFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) = UseCarSubmitFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }
}